<template>
  <div class="customer">
    <van-nav-bar
        title="外勤签到列表"
        left-arrow
        left-text="返回"
        @click-left="back"
    />
    <div style="width: 100%;height: 100%;background: #ffffff;margin-top: 10px">
      <van-list style="overflow: scroll">
        <div class="listColumn">
          <div>计划开始日期</div>
          <div>计划结束日期</div>
          <div>客户名称</div>
          <div>商机名称</div>
          <div>计划内容</div>
          <div>地址</div>
          <div>操作</div>
        </div>
        <div class="listItem" v-for="(task, index) in taskList" :key="index">
          <div>{{ task.fstarttime }}</div>
          <div>{{ task.fendtime }}</div>
          <div>{{ task.fcustomer }}</div>
          <div>{{ task.sjname }}</div>
          <div>{{ task.fnote }}</div>
          <div>{{ task.faddress }}</div>
          <div>
            <div class="btnWrapper">
              <a v-show="task.fstatus ==0" class="btn1" @click="toSignin(task)">签到</a>
              <a class="btn2" @click="toReport(task)">汇报</a>
            </div>

          </div>
        </div>
      </van-list>
    </div>
    <!--汇报-->
    <van-dialog v-model="isShowReport" title="汇报" :show-cancel-button="false" :show-confirm-button="false">
      <van-form>
        <van-field
            readonly
            clickable
            v-model="reportObj.ftime"
            name="ftime"
            label="跟进日期"
            placeholder="跟进日期"
            @click="showFtimeClick"
        >
        </van-field>
        <van-field
            v-model="reportObj.fnote"
            name="fnote"
            label="跟进内容"
            placeholder="跟进内容"
        />
        <van-field
            readonly
            clickable
            v-model="reportObj.iscompletedName"
            name="iscompletedName"
            label="是否完成"
            placeholder="是否完成"
            @click="showIscompletedClick"
        />
        <van-field
            name="fattachment"
            label="附件"
            placeholder="附件">
          <template #input>
            <van-uploader accept="image/*,.pdf,.doc,.xls" :after-read="uploadAfter" :preview-image="false">
              <van-button icon="plus" type="info">上传文件</van-button>
            </van-uploader>
          </template>
        </van-field>
        <div class="uploadWrapper">
          <div class="uploadItem" v-for="(upload, index) in reportObj.fattachment" :key="index" @click="handlePreview(upload)">{{ upload.filepath }}</div>
        </div>
        <div style="margin: 16px;">
          <van-row :gutter="16">
            <van-col span="12">
              <van-button type="default" size="large" @click="onCancel()">取消</van-button>
            </van-col>
            <van-col span="12">
              <van-button type="info" size="large" @click="onSubmit()" :loading="loading" :disabled="loading">提交</van-button>
            </van-col>
          </van-row>


        </div>
      </van-form>
    </van-dialog>
    <!--日期选择-->
    <van-popup v-model="showFtimePicker" position="bottom">
      <van-datetime-picker
          v-model="currentDate"
          type="date"
          @confirm="onConfirmFtime"
          @cancel="showFtimePicker = false"
      />
    </van-popup>

    <van-popup v-model="showIsCompletedPicker" position="bottom">
      <van-picker
          show-toolbar
          value-key="label"
          :columns="typeColumns"
          @confirm="onIsCompletedConfirm"
          @cancel="showIsCompletedPicker = false"
      />
    </van-popup>
  </div>
</template>
<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script>
  import { mapState } from 'vuex'
  import { scheduleList, doSign, uploadFile, doReport } from '@/api/api'
  import { Notify, Dialog, Toast } from 'vant'
  import moment from "moment";
  var sha1 = require('js-sha1')
  export default {
    name: "signInList",
    components: {
    },
    data () {
      return {
        pid: '',
        fscheduleid: '',
        currentDate: '',
        showFtimePicker: false,
        showIsCompletedPicker: false,
        isShowReport: false,
        loading: false,
        reportObj: {
          ftime: '',
          iscompleted: '',
          iscompletedName: '',
          fnote: '',
          fattachment: [],
        },
        typeColumns: [{ key: 1,label: 'Y'}, { key: 0 ,label: 'N'}],
        taskList: []
      }
    },
    computed: {
      ...mapState({
        openId: state => state.user.openId,
        access_token: state => state.app.access_token,
        ticket: state => state.app.ticket,
        appId: state => state.user.appId
      })
    },
    mounted() {
      this.ConfigFn(this.ticket)
    },
    created () {
      this.getList(1)
    },
    methods: {
      showFtimeClick () {
        this.showFtimePicker = true
        this.currentDate = new Date()
      },
      onConfirmFtime(val) {
        this.reportObj.ftime = moment(val).format('YYYY-MM-DD')
        this.showFtimePicker = false
      },
      showIscompletedClick () {
        this.showIsCompletedPicker = true
      },
      onIsCompletedConfirm (val) {
        this.reportObj.iscompletedName = val.label
        this.reportObj.iscompleted = val.key
        this.showIsCompletedPicker = false
      },
      uploadAfter (file) {
        let formData = new FormData()
        formData.append('file', file.file);
        formData.append('bizPath', "crm");
        uploadFile(formData).then(res => {
          if (res.success) {
            this.reportObj.fattachment.push({
              filepath: res.message
            })
            Notify({ type: 'success', message: '上传成功', duration: 4000 })
          }else {
            Notify({ type: 'danger', message: res.result, duration: 4000 })
          }
        })
      },
      handlePreview (record) {
        let url = 'http://124.221.130.190:8081/hwerJK/sys/common/static/' + record.filepath
        window.open(url)
      },
      getList () {
        scheduleList().then(res => {
          if (res.success) {
            this.taskList = res.result
          }else {
            Notify({ type: 'danger', message: res.message, duration: 4000 })
          }

        })
      },
      //注入配置
      ConfigFn(JsapiTicket){
        var mytimestamp = (Date.parse(new Date())) / 1000
        var mynonceStr = sha1(String(mytimestamp)).substring(0, 16)
        var mysignature = 'jsapi_ticket=' + JsapiTicket + '&noncestr=' + mynonceStr + '&timestamp=' + mytimestamp + '&url=' + window.parent.location.href.split('#')[0]
        wx.config({
          beta: true,
          debug: false,
          appId: this.appId,
          timestamp: mytimestamp,
          nonceStr: mynonceStr,
          signature: sha1(mysignature),
          jsApiList: [
            'getLocation',
            'checkJsApi'
          ]
        })
        wx.error(function(res){
        })
        wx.ready(function(res){
        })
      },
      checkJsApi(api){//检测api是否可用
        return new Promise((rel,err)=>{
          wx.checkJsApi({
            jsApiList: [api],
            success: function(res) {
              if(res.checkResult&&res.checkResult.getLocation == false){
                Toast('微信版本较低，请升级后重试！')
                err('版本低')
              }else{
                rel(true)
              }
            }
          });
        })
      },
      //签到
      toSignin(task) {
        var that = this
        this.checkJsApi('getLocation').then((rel)=>{
          if(rel){
            wx.getLocation({
              type: 'wgs84',//默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
              success: (res) =>  {
                let lat = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                let lng = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                doSign({
                  id: task.id,
                  lat,
                  lng
                }).then(res => {
                  if (res.success) {
                    Dialog.alert({
                      title: '签到成功',
                      message: '签到地址:'+ res.result,
                    }).then(() => {
                      // on close
                      // this.loading = false
                      that.getList()
                    });
                  }else {
                    Notify({ type: 'danger', message: res.message, duration: 4000 })
                  }
                })
              }
            });
          }
        })
      },
      toReport (task) {
        this.isShowReport = true
        this.pid = task.fopportunityid
        this.fscheduleid = task.id
        this.reportObj = {
          fattachment: []
        }
      },
      onSubmit () {
        if (!this.reportObj.ftime) {
          Toast('请选择跟进日期！')
          return false
        }
        this.loading = true
        let { ftime, fnote, iscompleted} = this.reportObj
        let fattachment = this.reportObj.fattachment.map(item => item.filepath).join()
        doReport({
          ftime,
          fnote,
          iscompleted,
          fattachment,
          pid: this.pid,
          fscheduleid: this.fscheduleid
        }).then(res => {
          if (res.success) {
            this.loading = false
            this.getList()
            this.isShowReport = false
            Notify({ type: 'success', message: res.message, duration: 4000 })
          }else {
            this.loading = false
            Notify({ type: 'danger', message: res.message, duration: 4000 })
          }
        })
      },
      onCancel () {
        this.isShowReport = false
      },
      back () {
        this.$router.push({name: 'modules'})
      },
    }
  }
</script>

<style scoped>
  .customer{
    min-height: 100vh;
    background: #ffffff;
  }
  .listColumn{
    width: 1200px;
    display: flex;
    line-height: 45px;
    background: #eee;
  }
  .listColumn div:nth-of-type(1) {
    width: 150px;
  }
  .listColumn div:nth-of-type(2) {
    width: 150px;
  }
  .listColumn div:nth-of-type(3) {
    width: 300px;
  }
  .listColumn div:nth-of-type(4) {
    width: 100px;
  }
  .listColumn div:nth-of-type(5) {
    width: 100px;
  }
  .listColumn div:nth-of-type(6) {
    width: 200px;
  }
  .listColumn div:nth-of-type(7) {
    width: 200px;
  }
  .listItem{
    width: 1200px;
    display: flex;
    line-height: 38px;
    border-bottom: 1px solid #eeeeee;
  }
  .listItem div:nth-of-type(1) {
    width: 150px;
  }
  .listItem div:nth-of-type(2) {
    width: 150px;
  }
  .listItem div:nth-of-type(3) {
    width: 300px;
  }
  .listItem div:nth-of-type(4) {
    width: 100px;
  }
  .listItem div:nth-of-type(5) {
    width: 100px;
  }
  .listItem div:nth-of-type(6) {
    width: 200px;
  }
  .listItem div:nth-of-type(7) {
    width: 100px;
  }
  .btnWrapper {
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    align-items: center;
    color: #1989fa;
  }
  .btn1 {

  }
  .btn2 {

  }
  .uploadWrapper {
    display: flex;
    flex-direction: column;
    color: #1989fa;
    font-size: 14px;
  }
  .uploadItem {
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
</style>